package com.enhinck.dbutilweb.common.util;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author HUENBIN
 */

@Slf4j
public class DataTransformer {

    public static <F, T> List<T> transform(List<F> fList, Class<T> tClass) {
        if (null == fList) {
            return new ArrayList<>();
        }
        List<T> tList = new ArrayList<>(fList.size());
        for (F f : fList) {
            T t = null;
            try {
                t = tClass.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                throw new RuntimeException(e);
            }
            BeanUtils.copyProperties(f, t);
            tList.add(t);
        }
        return tList;
    }

    public static <F, T> Collection<T> transform(Collection<F> fList, Class<T> tClass) {
        if (null == fList) {
            return new ArrayList<>();
        }
        Collection<T> tList = new ArrayList<>(fList.size());
        for (F f : fList) {
            T t = null;
            try {
                t = tClass.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                throw new RuntimeException(e);
            }
            BeanUtils.copyProperties(f, t);
            tList.add(t);
        }
        return tList;
    }


    public static <F, T> T transform(F f, Class<T> tClass) {
        if (null == f) {
            return null;
        }
        T t = null;
        try {
            t = tClass.newInstance();
            BeanUtils.copyProperties(f, t);
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }


        return t;
    }


    public static <F, T> Page<T> transformPage(IPage<F> iPage, Class<T> tClass) {
        Page<T> result = new Page<>();
        if (null != iPage) {
            List<F> fList = iPage.getRecords();
            List<T> tList = transform(fList, tClass);
            BeanUtils.copyProperties(iPage, result);
            result.setRecords(tList);
        }

        return result;
    }


}
